package com.zsc.projectmanagementapi.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zsc.projectmanagementapi.pojo.Do.User;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 使用JWT生成Token
 */
public class JWTUtil {

    /**
     * 设置过期时间
     */
    // private static final long EXPIPE_TIME =  24 * 60 * 60 * 1000;
    private static final long EXPIPE_TIME =  6 * 60 * 60 * 1000;//6个小时

    /**
     * token的密钥
     */
    private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";

    /**
     * 校验token是否正确
     */
    public static boolean verify(String token) throws IOException {
        try{
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;

        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取token中的信息无需密钥也能获得，这里获取登录者的学号
     */
    public static String getUsername(String token){
        try{
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        }catch (Exception e){
            return null;
        }
    }

    public static String getUserAuthorityId(String token){
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build().verify(token);
//            DecodedJWT jwt = JWT.decode(token);
//            String authorityId = jwt.getClaim("authorityId").asString();
            Claim authorityId = verify.getClaim("authorityId");
            return authorityId.asInt().toString();
        }catch (Exception e){
            return null;
        }
    }


    /**
     * 生成签名
     * 普通用户
     * @param sysUsers
     * @return
     */
    public static String signUser(User sysUsers){
        try{
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIPE_TIME);
            //密钥及算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = new HashMap<>(2);
            header.put("typ","JWT");
            header.put("alg","HS256");
            //附带userId信息，生成签名
            return JWT.create()
                    .withHeader(header)
                    .withClaim("username",sysUsers.getUsername())
                    .withExpiresAt(date)  //设置过期时间
                    .sign(algorithm);
        }catch (Exception e){
            return null;
        }
    }

}
